package CuratorCtrl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Properties;
import java.util.Vector;

public class Util {
	public final static String VBOXM_CMD = "VBoxManage";
	public static boolean windows = false;

	public static boolean canWrite(String path){
		if(path ==null)return false;
		File file=new File(path);
		boolean ret=file.isDirectory();
		return ret;
	}
	
	
	public static String get_os_name() throws IOException {

		// TextIO.writefile("terminal.log");
		Properties props = System.getProperties();
		String osName = props.getProperty("os.name");
		if (osName.toUpperCase().indexOf("WINDOWS") >= 0) {
			osName = "WINDOWS";
			windows = true;
		}
		return osName;

	}

	public static void do_import_ge(String VMname, String path, int port,
			int mem,String targetPath) throws IOException {
		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			// TextIO.writefile("terminal.log");
			String[] command = new String[3];
			String vbx_cmd = VBOXM_CMD;
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";

			command[2] = vbx_cmd + " import " + path + " --vsys 0 --vmname "
					+ VMname + " --memory " + mem+" --unit 10 --disk "+targetPath+"/centos.vmdk --unit 11 --disk "+targetPath+"/curator.vmdk";
			System.out.print(command[2]);
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
			}
			out.close();

			// new Image(VMname, port, 512);

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public static Vector<String> read_VMlist() throws IOException {
		Vector<String> input = read_rawlist();
		Vector<String> output = new Vector<String>();
		for (int i = 0; i < input.size(); i++) {
			if (check_curator(input.get(i))) {
				output.add(input.get(i));
			}

		}
		return output;
	}

	public static boolean check_curator(String name) throws IOException {
		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " showvminfo \"" + name + "\"";
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				if (line.indexOf("Description:") >= 0) {
					String tmp = input.readLine();
					if (tmp.indexOf("<iscurator=true>") >= 0)
						return true;
					else
						return false;
				}

			}
			out.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}

	public static Vector<String> read_rawlist() throws IOException {
		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			Vector<String> output = new Vector<String>();
			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " list vms";
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				int end = line.indexOf('"', 1);
				output.add(line.substring(1, end));
			}
			out.close();

			return output;

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;

	}

	public static Vector<String> read_runninglist() throws IOException {
		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			// TextIO.writefile("terminal.log");
			Vector<String> output = new Vector<String>();
			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " list runningvms";
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				int end = line.indexOf('"', 1);
				output.add(line.substring(1, end));
			}
			out.close();

			return output;

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;

	}

	public static Image read_singleVM(String name) throws IOException {
		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			// TextIO.writefile("terminal.log");
			String vbx_cmd = VBOXM_CMD;

			Image ret = new Image();
			ret.setPort(7071);
			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " showvminfo \"" + name + "\"";
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			while ((line = input.readLine()) != null) {
				// if(found) {
				// System.out.println(line);
				// found=false;
				// /}
				FileWriter fstream = new FileWriter("terminal.log", true);
				BufferedWriter out = new BufferedWriter(fstream);
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				if (line.indexOf("Config file:") >= 0) {
					ret.setLoc(line.substring(17));
					System.out.println(line.substring(17));
				}
				if (line.indexOf("Memory size:") >= 0) {
					int end = line.indexOf("MB");
					System.out.println(line.substring(17, end));
					ret.setMem(Integer.parseInt(line.substring(17, end)));

					System.out.println(line.substring(17));
				}
				if (line.indexOf("Description:") >= 0) {
					String tmp = input.readLine();
					if (tmp.indexOf("I'm") >= 0)
						System.out.println(tmp);
				}
				out.close();

			}
			return ret;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;

	}

	public static void runVM(String name, boolean hide) throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			// TextIO.writefile("terminal.log");
			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[2] = vbx_cmd + " startvm " + "\"" + name + "\"";
			if (hide)
				command[2] += " -type vrdp";
			command[1] = "-c";

			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					process.getErrorStream()));
			String Error;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((Error = stdError.readLine()) != null) {
				try {
					// Create file

					out.write(Error + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				System.out.println(Error);
			}
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void closeVM(String name) throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[2] = vbx_cmd + " controlvm " + "\"" + name + "\""
					+ " poweroff";

			command[1] = "-c";

			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					process.getErrorStream()));
			String Error;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((Error = stdError.readLine()) != null) {
				try {
					// Create file

					out.write(Error + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				System.out.println(Error);
			}
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void change_mem(String name, int mem_size) throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[2] = vbx_cmd + " modifyvm " + "\"" + name + "\""
					+ " --memory " + mem_size;

			command[1] = "-c";

			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					process.getErrorStream()));
			String Error;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((Error = stdError.readLine()) != null) {
				try {
					// Create file

					out.write(Error + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				System.out.println(Error);
			}
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static rule[] getrules(String name) throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			// TextIO.writefile("terminal.log");
			Vector<rule> ret = new Vector<rule>();
			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " showvminfo " + name;
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				if (line.indexOf("NIC 1 Rule") >= 0) {
					// System.out.println(line);
					ret.add(new rule(line));
				}

			}
			rule[] retv = new rule[ret.size()];
			out.close();

			ret.toArray(retv);

			return retv;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	public static boolean apply_port(String vmname, String rule_name,
			int guest, int host) throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			Vector<rule> ret = new Vector<rule>();
			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			String rule = "\"" + rule_name + ",tcp,," + host + ",," + guest
					+ "\"";

			command[2] = vbx_cmd + " modifyvm " + vmname + " --natpf1 " + rule;
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
				if (line.indexOf("NIC 1 Rule") >= 0) {
					// System.out.println(line);
					ret.add(new rule(line));
				}

			}
			out.close();

			rule[] retv = new rule[ret.size()];

			ret.toArray(retv);

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}

	public static boolean delete_rule(String vmname, String rule_name)
			throws IOException {

		try {
			File f;
			f = new File("terminal.log");
			if (!f.exists()) {
				f.createNewFile();
			}

			String vbx_cmd = VBOXM_CMD;

			String[] command = new String[3];
			if (get_os_name().toUpperCase().equals("WINDOWS")) {
				command[0] = "cmd";
				vbx_cmd += ".exe";
			} else {
				command[0] = "sh";

			}
			command[1] = "-c";
			command[2] = vbx_cmd + " modifyvm " + vmname + " --natpf1 "
					+ "delete " + "\"" + rule_name + "" + "\"";
			Process process;
			if (windows) {
				process = Runtime.getRuntime().exec(command[2]);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			InputStreamReader ir = new InputStreamReader(
					process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			String line;
			FileWriter fstream = new FileWriter("terminal.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			while ((line = input.readLine()) != null) {
				try {
					// Create file

					out.write(line + "\n");
					// Close the output stream
				} catch (Exception e) {// Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
			}
			out.close();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return false;

	}

	public static boolean update_rule(String vmname, String rule_name,
			int guest, int host) throws IOException {
		boolean del = delete_rule(vmname, rule_name);
		boolean add = apply_port(vmname, rule_name, guest, host);
		return add && del;
	}

}
